var app=getApp();
var utils = require("../../utils/utils");
var Zan = require('../../components/zanui/index');
var P = require('../../utils/wxpage');
let  specifications = require('../../wxpage/specifications/specifications.js');
// P('index',{
//     comps:[detailCp],
//     data: {
var  detailCp = require('../../wxpage/tabBar/tabBar.js');
var  cartOperation = require('../../wxpage/cartOperation/cartOperation.js');
P('cart',{
    comps:[detailCp,cartOperation,specifications],
  data: {
      payFun:[
          {
              title:'微信支付',
              type:5,
              icon:'icon-weixinzhifu'
          },
          {
              title:'货到付款',
              type:3,
              icon:'icon-huodaofukuan'
          }
      ],
    tableNum:"",
    phone:"",
    noteContent:null,
    tableShow:false,
    noAddress:true,
    isCartData:false,
    ejectIshow:false,//   用餐方式
    elementToggle:'0',//   0 外卖 1店内  2一元购  3店内自提
    cartDataList: [],
    totalPrice: 0,
    totalCount: 0,
    movelength: 0,
    address: '',
    userName: '',
    OrderWay: '',
    cartIsHidden: false,
    cartIndexIsHidden: true,
    animationData: {},
    noFunction:'',
    conf:{},
    uName:"",
    payType:5,
    boxNum:null,//餐盒數量
    isSelected:true,
    specifShow:false,
    selectedData:[],//规格数据
    isLoadOk:false,
   dataIsNull:true,
      business:true,//是否营业
      distribution_money:'0.00',//配送费
      isOrder:true,//可否下单
      distributionText:'',//配送费说明文字
      isAddDis:false,//当前显示总金额 是否有加配送费
      psOpen:false,//是否开启配送费
  },
  //弹出框
  //填写桌号
  getTable:function(e){
      var that=this;
      switch (e.target.id){
          case 't-number':
              that.setData({
                  tableNum:e.detail.value
              });
              break;
          case 'phone':
              that.setData({
                  phone:e.detail.value
              });
              break;
          case 'u-name':
              that.setData({
                  uName:e.detail.value
              });
          case 'note-content':
              that.setData({
                  noteContent:e.detail.value
              });
              break;
      }
  },
  //操作购物车数量的
  operatings:function(e){
      ////////console.log('购物车页面的    操作购物车数量');
      if(e.currentTarget.dataset.specif){

          let specif=e.currentTarget.dataset.specif;
          utils.operating(e,this,specif);

      }else{
          utils.operating(e,this);
      }
    if(this.data.cartDataList.length<=0){
      this.setData({
        isCartData:false
      });
    }
  },
  onReady: function () {
    wx.setNavigationBarTitle({
      title: '购物车'
    });
      //////////console.log('cartPage------------------------------');
      //////////console.log(this.data.cartDataList);
  },
  onLoad: function () {
      ////console.log('是否有购物车数据');
      ////console.log(this.data.dataIsNull);
    this.getShowConf();
  },
  onShow:function(){
    var that = this;
    app.getaddress(app.globalData.userid,that.getAddress);
  },
  getAddress:function(){
    utils.getAddress(this);
  },
  //更改用餐方式
  selectElement: function (e) {
      ////console.log('更改用餐方式----------------------');
      var that = this;
      let eId = e.currentTarget.id;
      let cType=e.currentTarget.dataset.type;
      let isboxFee=true;

      if(cType=='1'){
          isboxFee=false;
          that.setData({
              allPriceBox:false
          });
          ////console.log(that.allPriceBox);
      }
      if(cType!=this.data.elementToggle){
          ////////console.log('切换不重复');
          that.setData({
              elementToggle: cType
          });
          //////////console.log('消费方式');
          if(that.data.psOpen=='true'){
              //console.log('that.data.psOpen----------------------');
              //console.log(that.data.psOpen);
              that.setShowPrice();
          }
          if(isboxFee){
             ////console.log('有餐盒费用');
                  this.getLunchBox();
          }


      }else{
          //////////console.log('从复无效--------');
      }
  },
  addShopcartInCart: function (e) {
    let total_count = this.data.totalCount + 1;
    let addTarget = this.data.shoppingList.findIndex(item => item.name === e.target.dataset.name);
    this.data.shoppingList[addTarget].num++;
    let tempPrice = parseInt(this.data.totalPrice) + parseInt(this.data.shoppingList[addTarget].price)
    this.setData({
      shoppingList: this.data.shoppingList,
      totalPrice: tempPrice,
      totalCount: total_count
    })
  },
  //支付zz
  toCheck: function (e) {
    var that=this;

    //发起支付
    that.allOrder();
  },
  //提交订单
  allOrder: function () {
    var that = this;
    let isOrder;
    if(!that.data.isOrder && that.data.elementToggle==0){
        utils.modal('提示','消费金额低于起送费无法下单');
        return;
    }
    if(that.data.elementToggle=='1'){
        isOrder=that.isItIntact();
      var addressData={};
    }else{
        if(that.data.address){
            var addressData = that.data.address;
        }else{
            var addressData={};
        }
        //////console.log('地址信息');
        //////console.log(addressData);

    }
    var cartData = that.data.cartDataList;
    if (!that.data.address&&that.data.elementToggle=='0') {
        //////console.log('外卖地址为空');
      //弹窗
      wx.showToast({
        icon:'loading',
        title: '您的地址不完善 请检查'
      });
      return;
    };
    let priceText= that.data.allPriceBox?that.data.allPriceBox:that.data.allPrice;
    if(isOrder || that.data.elementToggle !='1'){
        wx.showModal({
            title: '提示',
            content: '总价' + priceText + "确认下单",
            success: function (res) {
                if (res.confirm) {
                    wx.showToast({
                        title: '正在下单',
                        icon: 'loading',
                        duration: 3000
                    });
                    //下单
                    var orderData = {};
                    for (var i = 0; i < cartData.length; i++) {
                        for (var s = 0; s < cartData[i].buydata.length; s++) {
                            // cartData[i].buydata[s].buy_property = ;
                             cartData[i].buydata[s].discount = 1;
                            cartData[i].buydata[s].integral = "10";
                            cartData[i].buydata[s].YN_full_buynum = 1;
                            cartData[i].buydata[s].boxfee = "0.00";
                        }
                    }
                     addressData.noteContent = that.data.noteContent;
                    // addressData.noteContent = "";
                    addressData.paytype = that.data.payType;
                    addressData.orderid = "";
                    //addressData.orderType = "1";
                    addressData.allboxfee = that.data.getBox;
                    addressData.id = "";
                    addressData.defaultAddress = "";
                    //给orderData加参数
                    orderData.shopType = 0;
                    orderData.bigwho = app.globalData.who;
                    orderData.who = app.globalData.who;
                    orderData.cartCollect = 0;
                    orderData.buydata = cartData;
                    orderData.cartdata = addressData;
                    //堂食
                    if(that.data.elementToggle=='1') {
                        //////////console.log("堂食下单");
                        orderData.tabledata = {
                            name: that.data.tableNum,
                            id: ""
                        }
                    }
                    addressData.orderType = that.data.elementToggle;
                    orderData = JSON.stringify(orderData);
                    //发送请求
                    utils.http({
                        url: "order/orderadd/querytype/ajax",
                        data: {
                            data: orderData,
                            userid: app.globalData.userid
                        },
                        method: 'POST',
                        success: function (res) {
                            if(res.data.status==1){
                                utils.removeCart();
                                utils.getCart(that,true);
                                if(that.data.payType==3){
                                    utils.modal('下单成功','订单号为'+res.data.orderid);
                                    return;
                                }
                                that.setData({
                                    orderid: res.data.orderid
                                });
                                //支付
                                var utilsObj = {
                                    orderid: that.data.orderid,
                                    navigateUrl: "../store/index",
                                    callback:function(){
                                        ////////console.log('调用支付成功');
                                        utils.removeCart();
                                    }
                                };

                                //////////console.log(utilsObj);
                                utils.pay(utilsObj);
                            }else{
                                utils.modal('下单失败',res.data.info);
                            }
                        },
                        header: {
                            // 'content-type': 'application/json'
                            'content-type': 'application/x-www-form-urlencoded'
                        },
                        fail: function (err) {
                        }
                    });
                } else if (res.cancel) {

                }
            }
        });
    }


  },
    //选择付款方式
    choicePay:function(e){
        this.setData({
            payType:e.currentTarget.id
        });
    },
  //监听下拉
  onPullDownRefresh:function(){
    ////////////////console.log("下拉刷新");
    wx.stopPullDownRefresh();
  },
    //获得动态高
    ////////////////////////新增功能//////////////////////////////////////
    //拿到店铺的个性化设置
    getShowConf:function() {
      var that=this;
        // ////console.log('读取商铺个性化设置');
        // ////console.log(app.globalData.userid);
        //请求1
        let httpData = {
            url: 'FreshTwo/confdata',
            data: {
                who: app.globalData.who,
                from: 'wxapp11',
                userid:app.globalData.userid
            },
            success:(res)=>{
                //////////console.log('请求成功');
                if (res.data.status == 1) {
                    let conf2=res.data;
                    conf2.conf.my_Definition=conf2.conf.time_YN_isOpenTime+conf2.conf.time_YN_time_order>=1?true:false;
                    //////////console.log('是否正在营业设置好的');
                    //////////console.log(conf2.conf.my_Definition);
                    that.setData({
                        conf2,
                        business:!conf2.conf.my_Definition
                    });

                    //查看默认用餐
                    //
                    if(that.data.conf2.conf.YN_shopinside_def==1){
                        ////console.log('默认店内用餐');
                        that.setData({
                            elementToggle:'1',
                            allPrice:(parseFloat(this.data.allPrice)-that.data.getBox).toFixed(2),
                        });
                    }
                    if(that.data.elementToggle=='0'){
                        ////console.log('外卖');
                    }
                    ////console.log('个性化数据拿到--------------------');
                    utils.getCart(this,true);
                    // that.getLunchBox();
                    //测试
                    conf2.conf.my_Definition=conf2.conf.shoptimeStatus+conf2.conf.time_YN_time_order>=1?true:false;
                    //是否打烊
                    var GGsysInfo = wx.getSystemInfoSync();//获取设备信息
                    ////////////console.log(GGsysInfo.windowHeight);

                    that.setData({
                        conf2,
                        setHeight:GGsysInfo.windowHeight
                    });
                    if(conf2.conf.my_Definition){
                        that.setData({
                            business:conf2.conf.my_Definition,
                            setHeight:GGsysInfo.windowHeight
                        });
                    }
                    that.setData({
                        //business:conf2.conf.my_Definition
                    })
                    ////////console.log('营业时间');
                    let time=that.data.conf2.conf.shop_time;
                    let timeText='';
                    ////////console.log(time);
                    time.forEach(function(value,index,arr){
                        ////////console.log(value);
                        if(value!='0'){

                            timeText+=value;
                            if(index%2==0){
                                ////////console.log(index);
                                ////////console.log('能整除');
                                timeText+=':'
                            }else{
                                timeText+='-'
                            }
                        }else{

                        }
                    });
                    timeText=timeText.substring(0,timeText.length-1);
                    //break
                    let message=false;
                    if(conf2.conf.shoptimeStatusTxt!=""&&conf2.conf.shoptimeStatusTxt!=null){
                        message=conf2.conf.shoptimeStatusTxt;
                    }
                    this.setData({
                        timeText,
                        message
                    });
                    //保存营业时间信息

                }else{

                }
            },
            fail:(err)=> {
                //////////console.log(err);
            }
        };
        //请求2
        let httpData2={
          url:'FreshTwo/cart_data',
          data:{
            who:app.globalData.who
          },
          method:'POST',
          success:(res)=>{
              //////////console.log('success ');
              //整理要用到的数据
              let conf1=res.data;
              that.setData({
                   conf1,
              });
              //如果只开启一种就餐方式
             if(conf1.conf.YNtakeout+conf1.conf.YNshopinside==1){
               //设置动态的消费方式选中
             }

             //是否开启配送费
              //配送费方法
              that.DistributionLogic(conf1.area);
             // if(conf1.area)
          },
          fail:(err)=>{
            //////////console.log(err);
          }
        }
        utils.http(httpData);
        utils.http(httpData2);
    },
    ////////////////////////新增功能//////////////////////////////////////
    //堂食信息是否完整
    isItIntact:function() {
       let texts=this.data.conf1.table.table_name==''?'桌号':this.data.conf1.table.table_name;
        // conf.NameClosed=0;//店内用餐的姓名是否要关闭  1关闭   0不关闭
        // conf.TelClosed=0;//店内用餐的电话是否关闭不显示  1关闭   0不关闭
        // conf.YN_simple=0;//桌号是否开启   1开启  0关闭
        //////////console.log('堂食信息是否完整');
        let data = this.data.conf1;
        if (data.inside.YN_must_name == 1 && this.data.uName == "") {
            wx.showToast({
                title: '姓名不完整'
            });
            return false;
        } else if (data.inside.YN_must_tel == 1 && this.data.phone == "") {
            wx.showToast({
                icon: 'loading',
                title: '电话不完整'
            });
            return false;
        } else if (data.table.YN_simple == 1&& this.data.tableNum == "") {
            wx.showToast({
                icon: 'loading',
                title: texts+'不完整'
            });
            return false;
        }else{
          return true;
        }
    },
    //购物车中显示规格区域
    showSpecif:function(e){
        let that=this;
        //////////console.log('显示规格区域');
        //////////console.log(e);
        this.setData({
            specifShow:true,
            pic:e.currentTarget.dataset.pic
        });
        let pId=e.currentTarget.id;
        //////////console.log(pId);
        pId=pId.split(':');
        //////////console.log(pId);
        that.getDetail(pId);
    },
    //获得商品详情
    getDetail:function(pId){
        var that=this;
        //获得商品详情
        let httpData={
            url:'FreshTwo/productdetails',
            data:{
                id:pId[0],
                showfullpicsrc:1
            },
            success:function(res){
                //////////console.log('success');
                ////////console.log(res.data.shopdetail.property);
                let property=res.data.shopdetail.property;

                let obj = JSON.parse(property);
                res.data.shopdetail.property=obj;
                if(res.data.info=='已查询到'){
                    //////////console.log('success   1');
                    //////////console.log(res.data);
                    that.setData({
                        specifData:res.data.shopdetail,
                    });
                    //////////console.log(obj);
                    that.adjustment(pId);


                }else{
                    utils.modal('提示',res.data.info);
                }

            },
            fail:function(err){
                utils.modal('提示',err);
            }
        };
        utils.http(httpData);
    },
    //根据 规格信息 调好样式
    adjustment:function(pId){
        //////////console.log('调好样式');
         //////////console.log(pId);
         pId.splice(0,1);
         ////////console.log(pId);
         pId.forEach(function(value,index,arr){
             let arrs=value.split('-');
             pId[index]=arrs;
             ////////console.log(arrs);
         });
         ////////console.log(pId);
        ////////console.log('规格数据数组');
         this.setData({
             attrData:pId
         });
         ////////console.log('保留的数据');
         ////////console.log(this.data.attrData);
    },
    //配送费逻辑
    DistributionLogic(data){
        let dataS=data.Data;
        if(dataS.length==1){
            dataS=dataS[0];
            ////console.log(dataS.startPrice);
            ////console.log(dataS.rule);
            let obj={
                staPrice:dataS.startPrice,
                type:dataS.rule,
                price:dataS.price,
            }
            //console.log('是否开启------------配送费');
            //console.log(dataS.open);
            this.setData({
                setShowPriceData:obj,
                //测试
                psOpen:dataS.open
                // psOpen:'false'
            });
        }

    },
    //根据配送费调整 显示价格
    setShowPrice(){
        let allPrice=this.data.allPrice;
        let obj=this.data.setShowPriceData;
        //console.log('用餐方式');
        //console.log(this.data.elementToggle);
        if(this.data.elementToggle!=0){
            //console.log('不是外卖');
            if(this.data.isAddDis){
                this.setData({
                    allPrice:utils.round2(parseFloat(allPrice)-parseFloat(obj.price)),
                    distribution_money:'0.00',
                    isAddDis:false,
                });
                //console.log('修改后的数据');
                //console.log(this.data.distributionText);
            }
            this.setData({
                distributionText:''
            });
            return;
        }
        // obj.type='3';
        // obj.staPrice=40;
        // obj.price=5;
        switch(obj.type){
            case '0':
                ////console.log('0');
                break;
            case '1':

                //设置配送说明
                if(this.data.distributionText==''){
                    var str='收取配送费'+utils.round2(obj.price)+'元';
                    this.setData({
                        distributionText:str,
                    });
                }

                //所有客户均收取配送费用
                //console.log('1 所有客户均收取配送费用-----------------------------------');
                this.setData({
                    distribution_money:this.data.setShowPriceData.price,
                     allPrice:parseFloat(this.data.allPrice)+parseFloat(obj.price),
                    isAddDis:true
                });
                //console.log('配送费');
                //console.log(this.data.distribution_money);
                //console.log(this.data.allPrice);
                break;
            case '2':
                //console.log('低于起送价格才收配送费用');
                //低于起送价格才收配送费用

                //设置配送说明
                if(this.data.distributionText==''){
                    var str= '消费金额低于'+utils.round2(obj.staPrice)+'收取配送费'+utils.round2(obj.price)+'元';
                    this.setData({
                        distributionText:str,
                    });
                }

                if(parseFloat(allPrice)<parseFloat(obj.staPrice)){
                    //console.log('低于起送价');
                    this.setData({
                        distribution_money:this.data.setShowPriceData.price,
                        allPrice:parseFloat(this.data.allPrice)+parseFloat(obj.price),
                        isAddDis:true,
                    });
                }else{
                    this.setData({
                        distribution_money:'0.00',
                        isAddDis:false
                    });
                }
                break;
            case '3':
                //低于起送价格不允许下单
                //console.log('低于起送价格不允许下单');

                if(this.data.distributionText==''){
                    var str= '消费金额低于'+utils.round2(obj.staPrice)+'不配送';
                    this.setData({
                        distributionText:str,
                    });
                }

                if(parseFloat(allPrice)<parseFloat(obj.staPrice)){
                   this.setData({
                       isOrder:false,
                       distribution_money:'0.00',
                       isAddDis:false,
                   });
                }else{
                    this.setData({
                        isOrder:true,
                        distribution_money:this.data.setShowPriceData.price,
                        allPrice:parseFloat(this.data.allPrice)+parseFloat(this.data.setShowPriceData.price),
                        isAddDis:true,
                    });
                }
                break;
        }
    },
    //如果是外卖配送计算餐盒费
    getLunchBox:function(operation){
        let num=0;
        if(this.data.cartDataList[0]){
            let cartData=(this.data.cartDataList[0].buydata);
            if(this.data.cartDataList!=[]){
                for (var i=0;i<cartData.length;i++){
                    num+= cartData[i].buyNum*cartData[i].boxfee;
                }
            }
            ////console.log(this.data.elementToggle);
            if(this.data.elementToggle!='1'){
                //console.log('不是店内 加餐盒费------------------');
                //console.log(parseFloat(this.data.allPrice));
                this.setData({
                    getBox:num.toFixed(2),
                    allPriceBox:(parseFloat(this.data.allPrice)+num).toFixed(2),
                    nums:num
                });
                //console.log(this.data.allPriceBox);
                //console.log(this.data.getBox);
            }else{
                ////console.log('是店内用餐');
                //////////console.log('堂食------------------');
                this.setData({
                    allPriceBox:undefined
                })
            }
        }
        ////console.log('餐盒费');
        ////console.log(num);
        // //////////console.log('获取购物车成功的回调');
        // //////////console.log(this.data.cartDataList);
    },


});
